<?php

namespace app\home\controller;

// 引入公共控制器
use app\common\model\Subject\Order;
use think\Controller;

class Subject extends Controller
{
    public function __construct()
    {
        parent::__construct();

        //保存一个模型
        $this->BusinessModel = model('Business.Business');
        $this->SubjectModel = model('Subject.Subject');
        $this->RecordModel = model('Business.Record');
        $this->OrderModel = model('Subject.Order');
        $this->CommentModel = model('Subject.Comment');
        $this->ChapterModel = model('Subject.Chapter');
        $this->RecordModel = model('Business.Record');
    }
    // 搜索
    public function search()
    {
        //是否为异步请求
        if ($this->request->isAjax()) {
            $page = $this->request->param("page", 1, "trim");
            $limit = $this->request->param("limit", 5, "trim");
            $search = $this->request->param("search", '', "trim");

            $where = [];

            // 如果关键词不为空就给条件
            if (!empty($search)) {
                $where['title'] = ['LIKE', "%$search%"];
            }

            // 偏移量
            $start = ($page - 1) * $limit;

            // 数据
            $count = $this->SubjectModel->where($where)->count();
            $list = $this->SubjectModel
                ->with(['category'])
                ->where($where)
                ->order('id')
                ->limit($start, $limit)
                ->select();

            //打印这个模型执行语句结构
            // echo $this->SubjectModel->getLastSql();
            // exit;    

            // 打印多条
            // var_dump(collection($list)->toArray());
            // exit;

            // 返回结果
            $data = [
                'list' => $list,
                'count' => $count,
            ];
            if ($list) {
                //tp会自动判断你的请求是ajax还是post 
                // 如果是ajax会自动将跳转方法，会自动转换为json结果返回
                $this->success('请求成功', null, $data);
                exit;
            } else {
                $this->error('暂无数据', null, $data);
                exit;
            }
        }
        return $this->view->fetch();
    }
    // 详情页
    public function details()
    {
        // $this->view->login['email']
        
        // 限制显示的评论条数
        $limit = 3;
        // 课程id
        $cid = $this->request->param('cid', '0', 'trim');
        // 登录用户的id
        // 判断是否有登录 其他控制器方法
        $controller = new \app\common\controller\Home(false);
        $business = $controller->IsLogin(false);
        
        $business = $controller->IsLogin(false);
        // if (!$business) {
        //     $this->error('请先登录');
        //     exit;
        // }
        $busid = 0;
        $auth='';
        
        if($business){
            $busid = $business['id'];
            $auth = $business['auth'];
        }
        // var_dump($busid);

        // 接收查看更多评论的请求
        if ($this->request->isAjax()) {
            // 接收查看更多评论的课程id
            $subid = $this->request->param('subid', '0', 'trim');

            // 查询总共有多少条评论
            $count = $this->CommentModel
                ->with(['business'])
                ->whereIn('subid', $subid)
                ->count();

            // 查询剩下未显示的评论
            $commentlist = $this->CommentModel
                ->with(['business'])
                ->whereIn('subid', $subid)
                ->order('createtime asc')
                ->limit($limit, $count)
                ->select();

            // 返回请求结果
            $result = $this->success('请求成功', null, $commentlist);
        }
        // 查询课程
        $subject = $this->SubjectModel->with(['category'])->find($cid);
        if (!$subject) {
            $this->error('查询课程不存在');
            exit;
        }

        // 查询该课程所有的用户评论的条数
        $count = $this->CommentModel->with(['business'])->whereIn('subid', $cid)->count();

        // 查询课程章节
        $chapterlist = $this->ChapterModel->where('subid', $cid)->select();

        // 限制输出3条数据
        $commentlist = $this->CommentModel
            ->with(['business'])
            ->whereIn('subid', $cid)
            ->order('createtime asc')
            ->limit($limit)
            ->select();

        // 把点赞数据从字符串转为数组，并向前端页面输出
        $likes = explode(',', $subject['likes']);
        $likes = json_encode($likes);

        // 变量赋值
        $this->assign([
            'subject' => $subject,
            //课程数据
            'chapterlist' => $chapterlist,
            //章节数据
            'commentlist' => $commentlist,
            //评论数据
            'likes' => $likes,
            //点赞数组
            'busid' => $busid,
            //当前登录的用户id
            'limit' => $limit,
            //限制显示的评论条数
            'count' => $count, //评论总条数
            'auth'=>$auth
        ]);
        return $this->view->fetch();

    }

    // 点赞功能
    public function likes()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            // 判断是否有登录 其他控制器方法
            $controller = new \app\common\controller\Home(false);
            $business = $controller->IsLogin(false);
            if (!$business) {
                $this->error('请先登录');
                exit;
            }

            $busid = isset($business['id']) ? $business['id'] : 0;
            $subject = $this->SubjectModel->find($params['subid']);
            $likes = explode(',', $subject['likes']);

            if ($params['action'] == 'red' && !in_array("$busid", $likes)) {
                array_unshift($likes, "$busid");

                $data = [
                    'id' => $params['subid'],
                    'likes' => implode(',', $likes),
                ];
                $result = $this->SubjectModel->isUpdate(true)->save($data);
                // $result=$this->success($data);
                if ($result) {
                    $this->success("点赞成功", "", $data);
                } else {
                    $this->error("点赞失败", '', $data);
                }
            } else if ($params['action'] == 'gray' && in_array("$busid", $likes)) {

                $key = array_search("$busid", $likes);
                array_splice($likes, $key, 1);

                $data = [
                    'id' => $params['subid'],
                    'likes' => implode(',', $likes),
                ];

                $result = $this->SubjectModel->isUpdate(true)->save($data);
                if ($result) {
                    $this->success("取消点赞成功", '', $data);
                } else {
                    $this->error("取消点赞失败", '', $data);
                }
            }
        }
    }
    // 订单
    public function order()
    {
        if ($this->request->isAjax()) {
            $busid = $this->request->param('busid', '0', 'trim');
            $page = $this->request->param("page", 1, "trim");
            $limit = $this->request->param("limit", 1, "trim");
            // 偏移量
            $start = ($page - 1) * $limit;
            $list = $this->OrderModel
                ->with(['subject'])
                ->where('busid', $busid)
                ->order('id')
                ->limit($start, $limit)
                ->select();
            // echo $this->SubjectModel->getLastSql();
            // exit;  
            $data = [
                'list' => $list,
            ];
            // var_dump(collection($news)->toArray());
            // exit;
            if ($list === NULL) {
                $this->error('暂无数据', null, $data);
                exit;
            } else {
                $this->success('请求成功', null, $data);
                exit;
            }

        }
        $busid = $this->request->param('busid', '0', 'trim');
        $business = $this->BusinessModel->where('id', $busid)->find();

        $this->assign([
            'business' => $business,
        ]);
        return $this->view->fetch();
    }
    public function record()
    {
        if ($this->request->isAjax()) {
            $busid = $this->request->param('busid', '0', 'trim');
            // 数据

            $page = $this->request->param("page", 1, "trim");
            $limit = $this->request->param("limit", 1, "trim");
            // 偏移量
            $start = ($page - 1) * $limit;
            $list = $this->RecordModel
                ->where('busid', $busid)
                ->order('id')
                ->limit($start, $limit)
                ->select();

            $data = [
                'list' => $list,
            ];
            if ($list) {
                $this->success('请求成功', null, $data);
                exit;
            } else {
                $this->error('暂无数据', null, $data);
                exit;
            }
        }

        $busid = $this->request->param('busid', '0', 'trim');
        $business = $this->BusinessModel->where('id', $busid)->find();
        
        $this->assign([
            'business' => $business,
            
        ]);
        return $this->view->fetch();
    }
    public function comment()
    {
        $business = cookie('business') ? cookie('business') : [];
        // echo $business['id'];
        // exit;
        $cid = $this->request->param('cid', '0', 'trim');
        $subject = $this->SubjectModel->where('id', $cid)->find();
        $list = [];
        $chapterlist = $this->ChapterModel->where('subid', $cid)->select();
        $list = array_column($chapterlist, 'id');

        $this->assign([
            'data' => $subject,
        ]);

        if ($this->request->isPost()) {

            $content = $this->request->param('content', '', 'trim');
            // echo $content;
            // echo '<br>';
            // echo mb_strlen($content);
            // exit;
            // 组装数据
            $data = [
                'content' => $content,
                'busid' => $business['id'],
                'subid' => $cid,
                'listid' => $list[0],
                'createtime' => time()
            ];
            $result = $this->CommentModel->save($data);
            if ($result) {
                $this->success('评论成功', url("/home/subject/details", ['cid' => $subject['id']]));
            } else {
                $this->error('评论失败');
            }
        }
        return $this->view->fetch();
    }

    // 购买完成
    public function buycomplete()
    {
        $business = cookie('business') ? cookie('business') : [];
        $busid = $business['id'];
        // halt($busid);
        $cid = $this->request->param('cid');
        $code = $this->request->param('code');

        $this->assign([
            'busid' => $busid,
            'cid' => $cid,
            'code' => $code
        ]);
        return $this->view->fetch();
    }
    public function buy()
    {

        if ($this->request->isAjax()) {
            $subid = $this->request->param('subid', 0, 'trim');

            $subject = $this->SubjectModel->find($subid);
            $chapter = $this->ChapterModel->where('subid', $subid)->find();
            if (!$chapter) {
                $this->error('无法购买，该课程暂无播放资源');
            }
            if (!$subject) {
                $this->error('当课程不存在');
                exit;
            }

            // 判断是否有登录 其他控制器方法
            $controller = new \app\common\controller\Home(false);
            $business = $controller->IsLogin(false);

            if (!$business) {
                $this->error('请先登录');
                exit;
            }
            $where = [
                'subid' => $subid,
                'busid' => $business['id'],
            ];
            $business = $this->BusinessModel->where('id', $business['id'])->find();

            // echo $business['deal'];
            // exit;
            $order = $this->OrderModel->where($where)->find();
            if ($order) {
                $result = $this->error('该课程已经购买过了', null, $order);
                exit;
            }

            // 用户余额
            $money = floatval($business['money']);
            // 课程价格
            $price = floatval($subject['price']);

            $Updatemoney = bcsub($money, $price);

            // 判断余额与课程价格的大小
            if ($Updatemoney < 0) {
                $result = $this->error('余额不足,请先充值');
            }

            // 事务 保证 一整套流程完整性
            // subject_order 订单表 insert 插入
            // business 客户表 update 更新
            // business_record 客户消费记录表 insert 插入

            // 开启操作表的事物
            $this->OrderModel->startTrans();
            $this->BusinessModel->startTrans();
            $this->RecordModel->startTrans();

            // 生成订单号
            $code = build_code("SUB");

            $OrderData = [
                'subid' => $subid,
                'busid' => $business['id'],
                'total' => $price,
                'code' => $code,
            ];
            $OrderStatus = $this->OrderModel->validate('common/Subject/Order')->save($OrderData);
            if ($OrderStatus === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            }

            //更新客户表的余额字段
            $validate = [
                [
                    'money' => ['require', 'number', '>=:0'],
                ],
                [
                    'money.require' => '余额字段未知',
                    'money.number' => '余额必须得是数字',
                    'money.>=' => '余额必须大于0元',
                ]
            ];

            $BusData = [
                'id' => $business['id'],
                'money' => $Updatemoney,
            ];
            if (!$business['deal']) {
                $BusData['deal'] = 1;
            }

            // 更新用户数据
            $BusStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusData);

            if ($BusStatus === FALSE) {
                //回滚的动作
                $this->OrderModel->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }
            // 插入消费记录表
            $subtitle = $subject['title'];
            $RecordData = [
                'total' => "-$price",
                'busid' => $business['id'],
                'content' => "购买了[{$subtitle}]课程,花费了￥{$price}元",
            ];

            $RecordStatus = $this->RecordModel->validate("common/business/Record")->save($RecordData);

            if ($RecordStatus === FALSE) {
                $this->BusinessModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            if ($OrderStatus === FALSE || $BusStatus === FALSE || $RecordStatus === FALSE) {
                $this->RecordModel->rollback();
                $this->BusinessModel->rollback();
                $this->OrderModel->rollback();
                $this->error("购买失败");
                exit;
            } else {
                $this->OrderModel->commit();
                $this->BusinessModel->commit();
                $this->RecordModel->commit();
                $this->success('购买成功');
                exit;
            }

        }
    }

    public function play()
    {
        if ($this->request->isAjax()) {
            $subid = $this->request->param('subid', 0, 'trim');
            $cid = $this->request->param('cid', 0, 'trim');

            $subject = $this->SubjectModel->find($subid);
            if (!$subject) {
                $this->error('当前课程不存在');
                exit;
            }

            // 判断是否有登录 其他控制器方法
            $controller = new \app\common\controller\Home(false);
            $business = $controller->IsLogin(false);

            if (!$business) {
                $this->error('请先登录');
                exit;
            }

            $order = $this->OrderModel->where(['subid' => $subid, 'busid' => $business['id']])->find();
            // halt($order->toArray());
            // var_dump($order);
            // exit;
            if (!$order) {
                $this->error('请先购买课程', null, ['buy' => true]);
                exit;

            }
            $where = [
                'subid' => $subid,
            ];
            if ($cid > 0) {
                $where['id'] = $cid;
            }

            $chapter = $this->ChapterModel->where($where)->order('id', 'asc')->find();

            if ($chapter) {
                $this->success('获取到章节信息', null, $chapter);
                exit;
            } else {
                $this->error('暂未找到章节信息');
                exit;
            }

        }

    }
}